package com.comba.data.export;

import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.commons.io.IOUtils;

import com.mysql.jdbc.Driver;

public class Main {

	public static void main(String[] args) throws Exception {
		String url = System.getProperty("jdbc.url");
		String username = System.getProperty("jdbc.username");
		String password = System.getProperty("jdbc.password");

		DriverManager.registerDriver(new Driver());

		Connection connection = DriverManager.getConnection(url, username, password);
		Statement statement = connection.createStatement();
		String sql = IOUtils.toString(Main.class.getClassLoader().getResourceAsStream("query.sql"));
		ResultSet rs = statement.executeQuery(sql);

		int columnCount = getColumnCount(sql);
		FileOutputStream output = new FileOutputStream("data.csv");
		StringBuilder rowBuilder = new StringBuilder();
		while(rs.next()) {
			for(int i=1; i<=columnCount; i++) {
				Object value = rs.getObject(i);
				if(value != null) {
					String stringValue = value.toString();
					if(stringValue.contains(",")) {
						stringValue = "\"" + stringValue + "\"";
					}
					rowBuilder.append(stringValue);
				} else {
					rowBuilder.append(value);
				}
				rowBuilder.append(",");
			}
			if(rowBuilder.length() > 0) {
				rowBuilder.setLength(rowBuilder.length() - 1);
				rowBuilder.append("\r\n");
			}
			IOUtils.write(rowBuilder.toString(), output, "GBK");
			rowBuilder.setLength(0);
		}

		output.close();
		rs.close();
		statement.close();
		connection.close();
	}


	public static int getColumnCount(String sql) {
		String upperCaseSql = sql.toUpperCase();
		int fromIndex = upperCaseSql.indexOf("FROM");
		String columnPartial = sql.substring(6, fromIndex);
		return columnPartial.split(",").length;
	}
}
